﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Threading;

namespace WpfWordsLearner.Triggers
{
	public sealed class PauseEventTrigger : System.Windows.Interactivity.EventTrigger
	{
		// Fields
		private EventArgs eventArgs;
		public static readonly DependencyProperty MillisecondsDelayProperty = DependencyProperty.Register("MillisecondsPerTick", typeof(double), typeof(PauseEventTrigger), 
																											new PropertyMetadata(1000.0));

		private DispatcherTimer timer;

		// Methods
		protected override void OnDetaching()
		{
			if (this.timer != null)
			{
				this.timer.Stop();
				this.timer = null;
			}
			base.OnDetaching();
		}

		protected override void OnEvent(EventArgs eventArgs)
		{
			if (this.timer != null)
			{
				this.timer.Stop();
			}
			this.eventArgs = eventArgs;

			this.timer = new DispatcherTimer();
			this.timer.Interval = TimeSpan.FromMilliseconds(this.MillisecondsDelay);
			this.timer.Tick += new EventHandler(this.OnTimerTick);
			this.timer.Start();
		}

		private void OnTimerTick(object sender, EventArgs e)
		{
			this.timer.Stop();

			base.InvokeActions(this.eventArgs);
		}

		// Properties
		public double MillisecondsDelay
		{
			get
			{
				return (double)base.GetValue(MillisecondsDelayProperty);
			}
			set
			{
				base.SetValue(MillisecondsDelayProperty, value);
			}
		}

	}
}
